﻿/*==============================
版本：v0.1
创建：2016.8.21
作者：洞庭夕照
博客:http://mzwhj.cnblogs.com
代码：https://git.oschina.net/ninesky/Ninesky
==============================*/

using System;
using System.Collections.Generic;
using Microsoft.Owin.Security;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using Ninesky.Core;
using Ninesky.Web.Areas.Member.Models;
using Ninesky.Auxiliary;

namespace Ninesky.Web.Areas.Member.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    public class UserController : Controller
    {
        private UserManager userManager = new UserManager();

        // GET: Member/User
        public ActionResult Index()
        {

            return View();
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterViewModel register)
        {
            if (userManager.HasUsername(register.UserName)) ModelState.AddModelError("UserName", "用户名已存在");
            if (userManager.HasEmail(register.Email)) ModelState.AddModelError("Email", "Email已存在");
            if (ModelState.IsValid)
            {
                var _user = new User()
                {
                    UserName = register.UserName,
                    Password = Security.SHA256(register.Password),
                    Sex = register.Sex,
                    Name = register.Name,
                    RoleID = 0,
                    Email = register.Email,
                    RegTime = System.DateTime.Now
                };
                var _resp = userManager.Add(_user);
                if (_resp.Code == 1)
                {
                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                }
                else ModelState.AddModelError("", _resp.Message);
            }
            return View(register);
        }


        /// <summary>
        /// 用户名是否可用
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <returns></returns> 
        [HttpPost]
        public JsonResult UsernameCan(string UserName)
        {
            return Json(!userManager.HasUsername(UserName));
        }

        /// <summary>
        /// Email是否存可用
        /// </summary>
        /// <param name="Email">Email</param>
        /// <returns></returns> 
        [HttpPost]
        public JsonResult EmailCan(string Email)
        {
            return Json(!userManager.HasEmail(Email));
        }
        public IAuthenticationManager AuthenticationManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }
    }
}